package com.zsk.okhttp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class PostTask implements IPostTask {

	protected OkHttpClient client;

	protected final static MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
	protected final static  MediaType formType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
	
	protected Map<String, String> jsonMap;
	protected String bodyStr;
	protected FormBody.Builder formBodyBuilder;
	protected Request.Builder requestBuilder;
	protected HttpUrl.Builder urlBuilder;

	public PostTask(OkHttpClient client, String url) {
		super();
		this.client = client;
		this.requestBuilder = new Request.Builder();
		this.urlBuilder = HttpUrl.parse(url).newBuilder();
	}

	@Override
	public ResData run() throws IOException {
		Request request = createRequest();
		return ResData.of(client.newCall(request).execute());
	}

	@Override
	public void run(Callback callback) {
		Request request = createRequest();
		client.newCall(request).enqueue(callback);
	}

	@Override
	public IPostTask addHeader(String key, String value) {
		requestBuilder.addHeader(key, value);
		return this;
	}

	@Override
	public IPostTask addFormData(String key, String value) {
		if (formBodyBuilder == null)
			formBodyBuilder = new FormBody.Builder();
		formBodyBuilder.add(key, value);
		return this;
	}

	@Override
	public IPostTask addJson(String key, String value) {
		if (jsonMap == null)
			jsonMap = new HashMap<>();
		jsonMap.put(key, value);
		return this;
	}

	@Override
	public IPostTask addJson(String json) {
		bodyStr = json;
		return this;
	}

	/**
	 * if bodyStr and jsonMap exist at the same time, bodyStr is used at first
	 * @return
	 */
	protected Request createRequest() {
		requestBuilder.url(urlBuilder.build());
		if (formBodyBuilder != null) {
			requestBuilder.post(formBodyBuilder.build());
		} else {
			//json request
			if (bodyStr!=null && !bodyStr.isEmpty()) {
				requestBuilder.post(RequestBody.create(jsonType,bodyStr));
			}else if(jsonMap!=null && jsonMap.size()>0) {
				requestBuilder.post(RequestBody.create(jsonType,JSON.toJSONString(jsonMap)));
			}else {
				requestBuilder.post(RequestBody.create(formType,""));
			}
			
		}
		Request request = requestBuilder.build();
		System.out.println(request.url().toString());
		return request;
	}

	@Override
	public IPostTask addQueryParam(String key, String value) {
		urlBuilder.addQueryParameter(key, value);
		return this;
	}

}
